package net.lab1024.util;

import net.lab1024.util.StringUtil;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.util.Map;

/**
 * HttpClient工具类
 *
 * @author listen
 * @date 2019年7月16日 15:45:32
 */
public class HttpClientUtil {

    /**
     * 请求编码
     */
    private static final String DEFAULT_CHARSET = "UTF-8";

    private HttpClient httpClient;

    public HttpClientUtil() {
        this.httpClient = initHttpClient();
    }

    public HttpClientUtil(HttpClient httpClient) {
        this.httpClient = httpClient;
    }

    public static CloseableHttpClient initHttpClient() {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(50);
        // 设置路由最高并发
        connectionManager.setDefaultMaxPerRoute(50);
        // 定义不活动的时间段（以毫秒为单位） 链接将被关闭
        connectionManager.setValidateAfterInactivity(2000);
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connectionManager).build();
        return client;
    }

    /**
     * 执行HTTP POST请求
     *
     * @param url  url
     * @param json 参数
     * @return
     */
    public String postWithJSON(String url, String json) {
        HttpPost httpPost = new HttpPost(url);
        if (StringUtil.isNotBlank(json)) {
            /**
             * 解决中文乱码问题
             */
            StringEntity entity = new StringEntity(json, DEFAULT_CHARSET);
            entity.setContentEncoding(DEFAULT_CHARSET);
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
        }

        try {
            HttpResponse resp = httpClient.execute(httpPost);
            if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 执行HTTP GET请求
     *
     * @param url   url
     * @param param 参数
     * @return
     */
    public String get(String url, Map<String, ?> param) {
        // 拼接参数
        if (null != param && !param.isEmpty()) {
            StringBuffer sb = new StringBuffer("?");
            for (String key : param.keySet()) {
                sb.append(key).append("=").append(param.get(key)).append("&");
            }
            url = url.concat(sb.toString());
            url = url.substring(0, url.length() - 1);
        }
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse resp = httpClient.execute(httpGet);
            if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}